package com.pengpai.pangucms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pengpai.pangucms.entity.SysUserRole;
import com.pengpai.pangucms.mapper.SysUserRoleMapper;
import com.pengpai.pangucms.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author lijunjie
 * @since 2023-07-30
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<Map<String, Object>> getUserRoleByUid(Integer userId) {
        return sysUserRoleMapper.getUserRoleByUid(userId);
    }

    @Override
    @Transactional
    public void grantByUid(Long userId, List<String> roleIds) {
        // 先删除已有权限
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        sysUserRoleMapper.delete(wrapper);
        // 再添加新权限
        for (String roleId : roleIds) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(Long.valueOf(roleId));
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
